package com.huige.wiki.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huige.wiki.entity.User;
import com.huige.wiki.entity.UserExample;
import com.huige.wiki.exception.BusinessException;
import com.huige.wiki.exception.BusinessExceptionCode;
import com.huige.wiki.mapper.UserMapper;
import com.huige.wiki.req.UserLoginReq;
import com.huige.wiki.req.UserQueryReq;
import com.huige.wiki.req.UserResetPasswordReq;
import com.huige.wiki.req.UserSaveReq;
import com.huige.wiki.resp.PageResp;
import com.huige.wiki.resp.UserLoginResp;
import com.huige.wiki.resp.UserQueryResp;
import com.huige.wiki.service.UserService;
import com.huige.wiki.util.CopyUtil;
import com.huige.wiki.util.SnowFlake;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    private static final Logger LOG = LoggerFactory.getLogger(UserService.class);

    @Resource
    private UserMapper userMapper;

    @Resource
    private SnowFlake snowFlake;

    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate redisTemplate;

    /**
     * 查询用户列表
     * @param req
     * @return
     */
    @Override
    public PageResp<UserQueryResp> list(UserQueryReq req) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        if(!ObjectUtils.isEmpty(req.getLoginName())){
            criteria.andLoginNameEqualTo(req.getLoginName());
        }
        // 设置分页参数
        PageHelper.startPage(req.getPage(),req.getSize());
        List<User> userList = userMapper.selectByExample(userExample);
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        LOG.info("总行数：{}",pageInfo.getTotal());
        LOG.info("总页数：{}",pageInfo.getPages());

        // 列表复制
        List<UserQueryResp> userQueryRespList = CopyUtil.copyList(userList, UserQueryResp.class);
        PageResp<UserQueryResp> pageResp = new PageResp<>();
        pageResp.setList(userQueryRespList);
        pageResp.setTotal(pageInfo.getTotal());

        return pageResp;
    }

    /**
     * 更新或者新增用户
     * @param req
     */
    @Override
    public void save(UserSaveReq req) {
        User user = CopyUtil.copy(req,User.class);
        if(ObjectUtils.isEmpty(req.getId())){
            // 新增前先判断用户名是否已经存在
            User userDB = selectByLoginName(req.getLoginName());
            if(ObjectUtils.isEmpty(userDB)){
                // 数据库不存在相同用户名，可以进行新增
                user.setId(snowFlake.nextId());
                userMapper.insert(user);
            }else{
                // 用户名已经存在，抛出异常。抛出RuntimeException异常不需要捕捉
                throw new BusinessException(BusinessExceptionCode.USER_LOGIN_NAME_EXIST);
            }

        }else{
            // 更新，不允许修改用户名和密码
            user.setLoginName(null);
            user.setPassword(null);
            // 有值才更新
            userMapper.updateByPrimaryKeySelective(user);
        }
    }

    /**
     * 删除用户
     * @param id
     */
    @Override
    public void delete(Long id) {
        userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public User selectByLoginName(String loginName) {
        UserExample userExample =new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andLoginNameEqualTo(loginName);
        List<User> userList = userMapper.selectByExample(userExample);
        if(CollectionUtils.isEmpty(userList)){
            return null;
        }else{
            return userList.get(0);
        }
    }

    /**
     * 重置用户密码。由前端传过来重置的密码
     * @param req
     */
    @Override
    public void resetPassword(UserResetPasswordReq req) {
        User user = CopyUtil.copy(req,User.class);
        userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 登录
     * @param req
     * @return
     */
    @Override
    public UserLoginResp login(UserLoginReq req) {
        User userDB = selectByLoginName(req.getLoginName());
        if(ObjectUtils.isEmpty(userDB)){
            LOG.info("用户名不存在，{}",req.getLoginName());
            throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
        }else{
            if(userDB.getPassword().equals(req.getPassword())){
                // 登录成功
                UserLoginResp userLoginResp = CopyUtil.copy(userDB,UserLoginResp.class);
                // 生成单点登录token，并放入redis中
                Long token = snowFlake.nextId();
                LOG.info("生成单点登录token: {} ，并放入redis中",token);
                userLoginResp.setToken(token.toString());
                redisTemplate.opsForValue().set(token.toString(), JSONObject.toJSONString(userLoginResp), 3600 * 24, TimeUnit.SECONDS);

                return userLoginResp;
            }else{
                LOG.info("密码不对，数据库密码：{}，输入密码：{}",userDB.getPassword(),req.getPassword());
                throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
            }
        }
    }
}
